package com.rc.saas.tenant.service.enterprise;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.exception.CustomException;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseMemberApplyMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseMemberMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseMemberRecordMapper;
import com.rc.saas.tenant.model.enterprise.*;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.RcMemberFlag;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.tenant.TenantUserExample;
import com.rc.saas.tenant.search.enterprise.EnterpriseMemberApplySearch;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.member.RcMemberFlagService;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.vo.enterprise.EnterpriseMemberApplyResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by sven on 2018-04-17
 */
@Service
public class EnterpriseMemberApplyServiceImpl implements EnterpriseMemberApplyService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private EnterpriseMemberApplyMapper enterpriseMemberApplyMapper;

    @Autowired
    private EnterpriseMemberMapper enterpriseMemberMapper;


    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private RcEnterpriseGainRecordService enterpriseGainRecordService;

    @Autowired
    private RcEnterpriseLevelSettingService enterpriseLevelSettingService;

    @Autowired
    private RcEnterpriseGainSettingService enterpriseGainSettingService;

    @Autowired
    private RcEnterpriseGainGradeSettingService enterpriseGainGradeSettingService;

    @Autowired
    private RcEnterpriseGainGradeRecordService enterpriseGainGradeRecordService;

    @Autowired
    private RcMemberFlagService memberFlagService;

    @Autowired
    private EnterpriseSubmemberApplyService enterpriseSubmemberApplyService;

    @Autowired
    private TenantRoleService tenantRoleService;


    @Override
    public EnterpriseMemberApplyMapper getMapper() {
        return enterpriseMemberApplyMapper;
    }

    @Override
    public PageInfo<EnterpriseMemberApplyResult> listPageEnterpriseMemberApply(EnterpriseMemberApplySearch search) {
        PageHelper.startPage(search.getOffset(), search.getLimit());
        List<EnterpriseMemberApplyResult> enterpriseMemberApplyResults = enterpriseMemberApplyMapper.listEnterpriseApply(search);

        enterpriseMemberApplyResults.stream()
                .filter(apply -> "1".equals(apply.getStatus())
                        && apply.getEnterpriseId() != null)
                .forEach(enterpriseMemberApplyResult -> {
                    EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectByPrimaryKey(enterpriseMemberApplyResult.getEnterpriseId());
                    enterpriseMemberApplyResult.setCreditAmount(enterpriseMember.getCreditAmount());
                    enterpriseMemberApplyResult.setRemainCreditAmount(enterpriseMember.getRemainCreditAmount());
                    enterpriseMemberApplyResult.setEnterpriseAccount(enterpriseMember.getEnterpriseAccount());
                    enterpriseMemberApplyResult.setGainAmount(enterpriseMember.getGainAmount());
                    enterpriseMemberApplyResult.setAllRechargeEnterpriseAccount(enterpriseMember.getAllRechargeEnterpriseAccount());
                    enterpriseMemberApplyResult.setEnterpriseStatus(enterpriseMember.getStatus());
                    enterpriseMemberApplyResult.setEnterpriseLevel(enterpriseMember.getEnterpriseLevel());

                });

        return new PageInfo<EnterpriseMemberApplyResult>(enterpriseMemberApplyResults);
    }

    @Override
    public TResponse saveApplyRecord(EnterpriseMemberApply enterpriseMemberApply, TenantUser user) throws CustomException {
//        TResponse tResponse = new TResponse();
//        EnterpriseMemberApply oldEnterpriseMemberApply = enterpriseMemberApplyMapper.selectByPrimaryKey(enterpriseMemberApply.getEnterpriseApplyId());
//        if ("0".equals(enterpriseMemberApply.getStatus())) {
//            tResponse.setStatus(600);
//            tResponse.setMessage("没有进行审核");
//            return tResponse;
//        }
//        if (!"0".equals(oldEnterpriseMemberApply.getStatus())) {
//            tResponse.setStatus(601);
//            tResponse.setMessage("无法重复审核");
//            return tResponse;
//        }
//
//        enterpriseMemberApplyMapper.updateByPrimaryKeySelective(enterpriseMemberApply);
//        if ("2".equals(enterpriseMemberApply.getStatus())) {
//            return TResponse.SUCCESS();
//        }
//        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(oldEnterpriseMemberApply.getMemberId());
//        EnterpriseMember enterpriseMember = new EnterpriseMember();
//        BeanUtils.copyProperties(oldEnterpriseMemberApply, enterpriseMember);
//        enterpriseMember.setAuditor(user.getLoginName());
//        enterpriseMember.setAuditTime(new Date());
//        enterpriseMember.setEnterpriseName(oldEnterpriseMemberApply.getEnterpriseName());
//        enterpriseMember.setEnterpriseMobile(memberInfo.getMobile());
//        enterpriseMember.setEnterpriseType(enterpriseMemberApply.getEnterpriseType());
//
//        enterpriseMemberMapper.insertReturnId(enterpriseMember);
//
//        Long enterpriseId = enterpriseMember.getEnterpriseId();
//
//        EnterpriseMemberRecord enterpriseMemberRecord = new EnterpriseMemberRecord();
//        enterpriseMemberRecord.setEnterpriseId(enterpriseId);
//        enterpriseMemberRecord.setEnterpriseMemberId(oldEnterpriseMemberApply.getMemberId());
//        enterpriseMemberRecord.setTenantCode(user.getTenantCode());
//        //记录类型 0 企业会员申请成功 1企业会员取消成功 默认0
//        enterpriseMemberRecord.setRecordType("0");
//        enterpriseMemberRecordMapper.insert(enterpriseMemberRecord);


        enterpriseMemberApplyMapper.updateByPrimaryKeySelective(enterpriseMemberApply);
        return TResponse.SUCCESS();
    }

    @Override
    public long countAllApply(String tenantCode) {
        EnterpriseMemberApplyExample example = new EnterpriseMemberApplyExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andStatusEqualTo("0");
        long count = enterpriseMemberApplyMapper.countByExample(example);
        return count;
    }

    @Override
    public void saveEnterpriseApply(EnterpriseMemberApply enterpriseMemberApply) {
        if (enterpriseMemberApply.getEnterpriseApplyId() == null) {
            enterpriseMemberApplyMapper.insertSelective(enterpriseMemberApply);
        } else {
            enterpriseMemberApplyMapper.updateByPrimaryKeySelective(enterpriseMemberApply);
        }
    }

    @Override
    public TResponse updateEnterpriseApplyForAudit(Long id, String status, String auditRemark) {
        EnterpriseMemberApply enterpriseApply = enterpriseMemberApplyMapper.selectByPrimaryKey(id);
        if ("1".equals(status)) {
            TenantUser isTenantUser = tenantUserService.selectByMobile(enterpriseApply.getPhone());
            if (isTenantUser != null) {
                logger.info("updateEnterpriseApplyForAudit,mobile:{}", enterpriseApply.getPhone());
                return TResponse.FAIL("审核失败,此手机号已存在");
            }

            EnterpriseMember enterprise = new EnterpriseMember();
            enterprise.setTenantCode(enterpriseApply.getTenantCode());
            enterprise.setMemberId(enterpriseApply.getMemberId());
            enterprise.setEnterpriseName(enterpriseApply.getEnterpriseName());
            enterprise.setEnterpriseMobile(enterpriseApply.getPhone());
            enterprise.setEnterpriseType("0");
            enterprise.setLicense(enterpriseApply.getEnterpriseCredit());
            enterprise.setAddress(enterpriseApply.getAddress());
            enterprise.setPhone(enterpriseApply.getPhone());
            enterprise.setTaxPayerCode(enterpriseApply.getTaxPayerCode());
            enterprise.setEnterpriseBank(enterpriseApply.getEnterpriseBank());
            enterprise.setEnterpriseBankAccount(enterpriseApply.getEnterpriseBankAccount());
            enterprise.setEnterpriseOwner(enterpriseApply.getEnterpriseOwner());
            enterprise.setOwnerMobile(enterpriseApply.getOwnerMobile());
            enterprise.setContactName(enterpriseApply.getContactName());
            enterprise.setCompanyImg1(enterpriseApply.getCompanyImg1());
            enterprise.setStatus("0");
            enterprise.setEnterpriseLevel("EV0");
            enterpriseMemberMapper.insertReturnId(enterprise);
            enterpriseApply.setEnterpriseId(enterprise.getEnterpriseId());


            //角色对象
            TenantRole tenantRole = tenantRoleService.selectByRoleType("3");
            //增加tenant_user账号
            TenantUser tenantUser = new TenantUser();
            tenantUser.setTenantCode(enterpriseApply.getTenantCode());
            tenantUser.setEnterpriseId(enterprise.getEnterpriseId());
            tenantUser.setUserType("3");
            tenantUser.setTenantRoleId(tenantRole.getTenantRoleId());
            tenantUser.setLoginName(enterpriseApply.getPhone());
            String saltPassword = MD5Utils.encrypt(enterpriseApply.getPhone(), enterpriseApply.getPhone());
            tenantUser.setPassword(saltPassword);
            tenantUser.setMobile(enterpriseApply.getPhone());
            tenantUser.setRealName(enterpriseApply.getEnterpriseOwner());
            tenantUserService.insertSelective(tenantUser);

            EnterpriseSubmemberApplyExample submemberApplyExample = new EnterpriseSubmemberApplyExample();
            submemberApplyExample.createCriteria().andEnterpriseNameEqualTo(enterpriseApply.getEnterpriseName()).andApplyStatusEqualTo("0");
            List<EnterpriseSubmemberApply> nopassApplyList = enterpriseSubmemberApplyService.selectByExample(submemberApplyExample);
            for (EnterpriseSubmemberApply submemberApply : nopassApplyList) {
                submemberApply.setApplyStatus("1");
                submemberApply.setEnterpriseId(enterprise.getEnterpriseId());
                enterpriseSubmemberApplyService.updateByPrimaryKeySelective(submemberApply);

                RcMemberFlag memberFlag = memberFlagService.selectByPrimaryKey(submemberApply.getMemberId());
                if (memberFlag != null) {
                    memberFlag.setEnterpriseId(enterprise.getEnterpriseId());
                    memberFlag.setIsEnterpriseLevel("1");
                    memberFlagService.updateByPrimaryKeySelective(memberFlag);
                } else {
                    memberFlag = new RcMemberFlag();
                    memberFlag.setEnterpriseId(enterprise.getEnterpriseId());
                    memberFlag.setIsEnterpriseLevel("1");
                    memberFlagService.insertSelective(memberFlag);
                }
            }

            RcEnterpriseGainSettingExample gainSettingExample = new RcEnterpriseGainSettingExample();
            gainSettingExample.createCriteria().andEnterpriseLevelEqualTo("EV0");
            List<RcEnterpriseGainSetting> gainSettingList = enterpriseGainSettingService.selectByExample(gainSettingExample);
            for (RcEnterpriseGainSetting gainSetting : gainSettingList) {
                RcEnterpriseGainRecord gainRecord = new RcEnterpriseGainRecord();
                gainRecord.setEnterpriseGainId(gainSetting.getEnterpriseGainId());
                gainRecord.setEnterpriseLevel(gainSetting.getEnterpriseLevel());
                gainRecord.setEnterpriseId(enterprise.getEnterpriseId());
                gainRecord.setMemberId(enterpriseApply.getMemberId());
                gainRecord.setGainName(gainSetting.getGainName());
                gainRecord.setGainType(gainSetting.getGainType());
                gainRecord.setGainLogo(gainSetting.getGainLogo());
                gainRecord.setSort(gainSetting.getSort());
                gainRecord.setRemark(gainSetting.getRemark());
                gainRecord.setStatus(gainSetting.getStatus());
                enterpriseGainRecordService.insertReturnId(gainRecord);

                RcEnterpriseGainGradeSettingExample gradeSettingExample = new RcEnterpriseGainGradeSettingExample();
                gradeSettingExample.createCriteria().andEnterpriseGainIdEqualTo(gainSetting.getEnterpriseGainId());
                List<RcEnterpriseGainGradeSetting> gradeSettingList = enterpriseGainGradeSettingService.selectByExample(gradeSettingExample);
                for (RcEnterpriseGainGradeSetting gradeSetting : gradeSettingList) {
                    RcEnterpriseGainGradeRecord gradeRecord = new RcEnterpriseGainGradeRecord();
                    gradeRecord.setEnterpriseGainRecordId(gainRecord.getEnterpriseGainRecordId());
                    gradeRecord.setEnterpriseGainId(gainSetting.getEnterpriseGainId());
                    gradeRecord.setEnterpriseId(enterprise.getEnterpriseId());
                    gradeRecord.setMemberId(enterpriseApply.getMemberId());
                    gradeRecord.setRechargeAmount(gradeSetting.getRechargeAmount());
                    gradeRecord.setDiscountAmount(gradeSetting.getDiscountAmount());
                    gradeRecord.setGainLogo(gradeSetting.getGainLogo());
                    enterpriseGainGradeRecordService.insertSelective(gradeRecord);
                }
            }
        }
        enterpriseApply.setStatus(status);
        enterpriseApply.setAuditRemark(auditRemark);
        enterpriseMemberApplyMapper.updateByPrimaryKeySelective(enterpriseApply);
        return TResponse.SUCCESS();
    }

    @Override
    public EnterpriseMemberApply selectByEnterpriseId(Long enterpriseId) {
        EnterpriseMemberApplyExample example = new EnterpriseMemberApplyExample();
        example.createCriteria().andEnterpriseIdEqualTo(enterpriseId);
        return enterpriseMemberApplyMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public void insertReturnId(EnterpriseMemberApply enterpriseMemberApply) {
        enterpriseMemberApplyMapper.insertReturnId(enterpriseMemberApply);
    }

    @Override
    public List<EnterpriseMemberApply> getEnterpriseMemberApplys(Long enterpriseId) {
        EnterpriseMemberApplyExample example = new EnterpriseMemberApplyExample();

        if (enterpriseId!=null){
            example.createCriteria().andStatusEqualTo("1").andEnterpriseIdEqualTo(enterpriseId);
        }else{
            example.createCriteria().andStatusEqualTo("1");
        }
        return enterpriseMemberApplyMapper.selectByExample(example);
    }
}
